#include "OptionsDialog.h"
#include "shlobj.h"
#include "objbase.h"
#include "Editor.h"
#include "Basic/FileSystem.h"

#pragma comment(lib, "ole32.lib")
#pragma comment(lib, "shell32.lib")

namespace FinalRendering
{
	namespace Editor
	{
		using namespace GxRendering::UI;
	
		OptionsDialog::OptionsDialog()
		{

			OnShow.Bind(this, &OptionsDialog::form_Show);

			SetClientWidth(500);
			SetClientHeight(350);
			SetBorder(GxWinGUI::fbFixedDialog);
			SetMinimizeBox(false);
			SetMaximizeBox(false);
			SetText(L"Editor Options");


			TabControl * tab = new TabControl();
			tab->Posit(10, 10, 480, 280);
			TabPage * pgGen = new TabPage();
			pgGen->SetText(L"General");
			tab->AddItem(pgGen);
			txtWorkPath = new TextBox();
			txtWorkPath->Posit(130, 20, 250, 20);
			pgGen->AddChild(txtWorkPath);
			ui->AddChild(tab);

			Label * lbl = new Label();
			lbl->SetText(L"Working Directory:");
			lbl->Posit(10, 22, 100, 20);
			pgGen->AddChild(lbl);

			Button * btn = new Button();
			btn->SetText(L"&OK");
			btn->Posit(350, 310, 60, 28);
			btn->OnClick.Bind(this, &OptionsDialog::btnOK_Clicked);
			ui->AddChild(btn);
			
			btn = new Button();
			btn->SetText(L"&Cancel");
			btn->Posit(420, 310, 60, 28);
			btn->OnClick.Bind(this, &OptionsDialog::btnCancel_Clicked);
			ui->AddChild(btn);

			btn = new Button();
			btn->SetText(L"Browse");
			btn->Posit(380, 20, 60, 20);
			btn->OnClick.Bind(this, &OptionsDialog::btnBrowse_Clicked);
			pgGen->AddChild(btn);

		}

		void OptionsDialog::form_Show(Object * sender, GxWinGUI::EventArgs e)
		{
			txtWorkPath->SetText(WorldEditor->Preference.WorkPath);
		}

		void OptionsDialog::btnOK_Clicked(UI_Base * sender)
		{
			if (FileExists(txtWorkPath->GetText()))
			{
				WorldEditor->Preference.WorkPath = txtWorkPath->GetText();
				WorldEditor->Preference.SavePreference();
				SetDialogResult(BaseForm::OK);
			}
			else
				MessageBox(L"Working directory not exists.", L"World Editor", MB_ICONEXCLAMATION);

			
		}

		void OptionsDialog::btnCancel_Clicked(UI_Base * sender)
		{
			SetDialogResult(BaseForm::Cancel);
		}

		void OptionsDialog::btnBrowse_Clicked(UI_Base * sender)
		{  
			BROWSEINFO   bi;   
			memset(&bi, 0, sizeof(BROWSEINFO));
			wchar_t path[MAX_PATH];
			memset(path, 0, sizeof(wchar_t)*MAX_PATH);
			ITEMIDLIST*   pidl = 0;   
			bi.hwndOwner = handle;   
			bi.pidlRoot=0;   
			bi.lpszTitle=_T("Choose a folder");   
			bi.ulFlags=BIF_RETURNONLYFSDIRS | BIF_EDITBOX | BIF_NEWDIALOGSTYLE;   
			bi.lpfn=0;   
			bi.iImage=0; 
			CoInitialize(0);
			if(pidl=SHBrowseForFolder(&bi))   
				SHGetPathFromIDList(pidl,path); 
			if (pidl)
			{
				txtWorkPath->SetText(path);
			}
			CoTaskMemFree(pidl);

			
		}
	}
}